import { anyObject, ComponentClass, ElementClass, IRootState } from "breeze-leaf-core-lib";
import { Dispatch } from "redux";
import { CommonActionType } from "../interface/state";
import { ServiceActionType } from "../utils/constant";

export const setDefaultRootState = (dispatch: Dispatch<CommonActionType>) =>
  (rootState: IRootState, component: ComponentClass) => {
    const _rootState = setDefaultValueForProps(component.view, rootState['$root'] || {})
    dispatch({
      type: ServiceActionType.StoreMutation,
      who: {
        name: component.name,
        uuid: component.uuid
      },
      which: {
        field: '*'
      },
      payload: { '$root': _rootState }
    });
  }

const setDefaultValueForProps = (element: ElementClass, values: anyObject) => {
  const props = element.getProps() || [];
  props.forEach(prop => {
    if (prop.field === 'defaultValue' || prop.field === 'initialValues') {
      element.name === 'Form'
        ? (Object.assign(values, prop.value))
        : Object.assign(values, { [element.field]: prop.value })
      element.deleteProp(prop.field);
    }
  });
  const children = element.getChildren();
  if (children && children.length > 0) {
    children.forEach(child => {
      setDefaultValueForProps(child, values);
    });
  }
  return values;
}